package com.kimoge.spring6.validation.methodone;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 * @author kimoge
 * @date 2025/8/30
 * @description
 */
public class PersonValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        // 确定所要校验的类
        return clazz.equals(Person.class);
    }

    @Override
    public void validate(Object target, Errors errors) {
        // 校验逻辑
        Person person = (Person) target;
        //1、姓名不为空
        ValidationUtils.rejectIfEmpty(errors, "name", "姓名不能为空");
        //2、年龄在0-100之间
        if (person.getAge() < 0) {
            errors.rejectValue("age", "年龄不能小于0");
        } else if (person.getAge() > 100) {
            errors.rejectValue("age", "年龄不能大于100");
        }
        //3、性别只能为男or女
        if (!person.getSex().equals("男")||!person.getSex().equals("女")) {
            errors.rejectValue("sex", "性别只有选择[男，女]");
        }
    }
}
